﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;
using System.Security.AccessControl;

public partial class Files : Parser
{
    string _type;
    string _extension;
    string _fileDesc;
    string _fullPath;
    static string _controlName;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //fullAccessFolder(Server.MapPath("/webcms"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/file/"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/image/"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/video/"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/document/"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/otherfile/"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/audio/"));
            //fullAccessFolder(Server.MapPath("/webcms/uploads/compressed/"));

            if (!IsPostBack)
            {
                string tmp = Request["return"] ?? string.Empty;
                if (tmp != "") _controlName = tmp;
            }
            InitAll();

            if (!CheckLogin()) Response.Redirect("login.aspx");
            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            _type = Request["type"] ?? "image";
            _fullPath = Request["fullPath"] ?? "false";

            if ((Request["action"] ?? "default") == "upload")
            {
                LoadFile("upload.html", false);
            }
            else
            {
                LoadFile("file.html", false);
            }

            switch (_type)
            {
                case "image": _extension = "*.jpg;*.jpeg;*.png;*.bmp;*.ico;*.gif"; _fileDesc = _parser.GetLabelValue("Image", _currentLanguage); break;
                case "audio": _extension = "*.mp3;*.wma;*.wav;*.mid;*.midi;*.flac;*.ape;*.m4a"; _fileDesc = _parser.GetLabelValue("Audio", _currentLanguage); break;
                case "compressed": _extension = "*.zip;*.rar;*.ace"; _fileDesc = _parser.GetLabelValue("Compressed", _currentLanguage); break;
                case "file": _extension = "*.*"; _fileDesc = _parser.GetLabelValue("OtherFiles", _currentLanguage); break;
                case "video": _extension = "*.avi;*.mpg;*.mpeg;*.mkv;*.mp4;*.vob;*.mov;*.ts;*.tp;*.m2ts"; _fileDesc = _parser.GetLabelValue("Video", _currentLanguage); break;
                case "document": _extension = "*.txt;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx;*.pdf;*.rtf"; _fileDesc = _parser.GetLabelValue("Document", _currentLanguage); break;
            }

            LoadFiles();
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadFiles()
    {
        try
        {
            string basePath = Request.MapPath(_parser.GetConfig("UploadPath", "~/uploads"));
            string filePath = Path.Combine(basePath, _type);
            string search = Request["search"] ?? string.Empty;

            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
            if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);

            string[] files = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);

            if (!string.IsNullOrEmpty(search)) //Search
            {
                files = files.Where(f => Path.GetFileName(f).ToLower().Contains(search.ToLower())).ToArray();
                _parser.Assign("searchValue", search);
            }

            if (_extension != "*.*") //Filter by extension
            {
                files = files.Where(f => _extension.Contains("*" + Path.GetExtension(f).ToLower())).ToArray();
            }

            List<FilesInfo> filesInfo = new List<FilesInfo>();

            filesInfo = files.Select(f => new FilesInfo()
            {
                FileName = Path.GetFileName(f),
                FileURL = f.Replace(Server.MapPath("~"), "").Replace("\\", "/"),
                FileSize = new FileInfo(f).Length,
                FileDate = new FileInfo(f).CreationTime
            }).ToList();

            filesInfo = filesInfo.OrderBy(f => f.FileName).ThenByDescending(f => f.FileDate).ToList();

            double totalRecord = files.Length;
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = 9;
            int totalPage = (int)(totalRecord / pageSize);

            if (totalPage * pageSize < totalRecord) totalPage++;

            _parser.Assign("uploadToFolder", _type);
            if (_fullPath == "true") _parser.Assign("fullPath", Path.GetDirectoryName(Request.Url.ToString()).Replace("\\", "/"));
            //_parser.Assign("returnObject", Request["return"] ?? string.Empty);
            _parser.Assign("returnObject", _controlName);
            _parser.Assign("fileExt", _extension);
            _parser.Assign("fileDesc", _fileDesc);

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("fileURL", filesInfo[i].FileURL);
                    _parser.Assign("fileName", filesInfo[i].FileName);
                    _parser.Assign("fileSize", filesInfo[i].FileSize.ToString("N0"));
                    _parser.Assign("fileDate", filesInfo[i].FileDate.ToShortDateString());
                    _parser.Parse("Main.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Table.Paging");
                _parser.Parse("Main.Table");
            }

            _parser.Parse("Main.Table");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
    private void fullAccessFolder(string url) {
        //string redirectionFolder = @"D:\test\subtest\";
        try
        {
            FileSystemAccessRule everyOne = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow);
            DirectorySecurity dirSecurity = new DirectorySecurity(url, AccessControlSections.Group);
            dirSecurity.AddAccessRule(everyOne);
            Directory.SetAccessControl(url, dirSecurity);
        }catch{}
    }
}

public class FilesInfo
{
    public string FileName { get; set; }
    public string FileURL { get; set; }
    public long FileSize { get; set; }
    public DateTime FileDate { get; set; }
}